package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;

    /**
     * 根据id保存或修改文章
     *
     * @param newsId
     */
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 根据newsId查询文章，并检查自媒体文章  wmNews
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装 ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        // 3. 保存或修改article信息
        saveOrUpdateApArticle(apArticle);
        // 4. 保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);
        // 5. TODO 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        // 6. 更新 wmNews状态  改为9  并设置articleId
        updateWmNews(newsId, wmNews, apArticle);
        // 7. TODO 通知es索引库添加文章索引

    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1.校验参数
        //页大小判断
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        //频道判断
        String tag = dto.getTag();
        if (StringUtils.isBlank(tag)) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间判断
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)
                && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2.执行请求
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        //遍历
        for (ApArticle apArticle : apArticleList) {
            // 获取文章封面字段
            String images = apArticle.getImages();
            //判断
            if (StringUtils.isNotBlank(images)) {
                // 将封面按照,号切割   生成流
                images = Arrays.stream(apArticle.getImages().split(","))
                        // 每一个路径添加前缀
                        .map(utl -> webSite + utl)
                        // 将加了前缀的路径  拼接成字符串
                        .collect(Collectors.joining(","));
                //设置
                apArticle.setImages(images);
                //拼接静态页面的前缀路径
                apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
            }
        }
        //3.返回结果
        return ResponseResult.okResult(apArticleList);
    }

    /**
     * 更新自媒体文章
     * 更新wmNews状态改为9
     * 并设置articleId
     *
     * @param newsId
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNews(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        //更新wmNews状态改为9
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        //更新articleId
        wmNews.setArticleId(apArticle.getId());
        ResponseResult updateResult = wemediaFeign.updateWmNews(wmNews);
        //校验状态码
        if (!updateResult.checkCode()) {
            log.error("文章发布失败 远程调用修改文章接口失败， 不予发布 , 文章id : {} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用修改文章接口失败");
        }

    }

    /**
     * 保存(添加)关联配置和内容信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        //1.添加关联配置
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        //2.添加关联内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    /**
     * 保存或修改文章信息
     *
     * @param apArticle
     */
    private void saveOrUpdateApArticle(ApArticle apArticle) {
        //判断wmNews是否关联articleId
        if (apArticle.getId() == null) {
            //如果为空，无关联，新增apArticle
            //保存文章
            apArticle.setCollection(0); // 收藏数
            apArticle.setLikes(0);// 点赞数
            apArticle.setComment(0);// 评论数
            apArticle.setViews(0); // 阅读数
            this.save(apArticle);
        } else {
            //如果有关联，修改apArticle
            //根据文章id查到文章
            ApArticle article = this.getById(apArticle.getId());
            //判断关联的文章是否存在
            if (apArticle == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            //修改apArticle
            this.updateById(apArticle);
            //修改文章后，删除原来关联的文章配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            //修改文章后，删除原来关联的文章内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    /**
     * 封装ApArticle
     * 设置频道和作者
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        //1.wmNews转为apArticle
        ApArticle apArticle = new ApArticle();
        //拷贝属性
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setId(wmNews.getArticleId());
        // 普通文章
        apArticle.setFlag((byte) 0);
        // 文章布局
        apArticle.setLayout(wmNews.getType());
        //2.设置频道
        //远程查询频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        //检查信息的状态码是否=200
        if (!channelResult.checkCode()) {
            log.error("文章发布失败，远程调用查询频道出现异常，无法发布，文章id: {} 频道id: {}"
                    , wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用查询频道出现异常");
        }
        AdChannel adChannel = channelResult.getData();
        if (adChannel == null) {
            log.error("文章发布失败，未查询到相关频道信息，无法发布，文章id: {} 频道id: {}"
                    , wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到频道信息");
        }
        //设置频道
        apArticle.setChannelName(adChannel.getName());
        //3.设置作者
        //查询作者
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("文章发布失败，未查询到相关作者信息，不予发布，文章id : {}  自媒体用户id : {}"
                    , wmNews.getId(), wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "根据自媒体用户，查询关联作者信息失败");
        }
        //设置作者id，作者名称
        apArticle.setAuthorId(apAuthor.getId().longValue());
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }

    /**
     * 查询并检查自媒体文章
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        //远程调用查询自媒体文章
        ResponseResult<WmNews> newsResult = wemediaFeign.findWmNewsById(newsId);
        //判断文章状态码是否是200
        if (!newsResult.checkCode()) {
            log.error("文章发布失败，远程调用自媒体文章接口失败，文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用自媒体文章接口失败");
        }
        //获取文章数据，判断
        WmNews wmNews = newsResult.getData();
        if (wmNews == null) {
            log.error("文章发布失败，未查询到自媒体文章，文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到自媒体文章");
        }
        //检查文章状态是否是4，8
        short status = wmNews.getStatus().shortValue();
        if (status != WmNews.Status.ADMIN_SUCCESS.getCode()
                && status != WmNews.Status.SUCCESS.getCode()) {
            log.error("文章发布失败，文章状态不为4和8，无法发布，文章id: {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自媒体文章状态错误");
        }
        return wmNews;
    }
}